package cn.wangliang181230.json.parser.jackson;

import cn.wangliang181230.json.parser.IJSONParser;
import cn.wangliang181230.json.parser.JSONParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonParser implements IJSONParser {

	private static final ObjectMapper mapper = new ObjectMapper();


	@Override
	public String toJSONString(Object obj) {
		try {
			return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new JSONParseException("obj转JSON字符串失败", e);
		}
	}

	@Override
	public <T> T parse(String jsonText, Class<T> targetClass) {
		try {
			return mapper.readValue(jsonText, targetClass);
		} catch (JsonProcessingException e) {
			throw new JSONParseException("JSON字符串转Bean失败", e);
		}
	}

}
